﻿using Core.Framework.Common;
using DotNetty.Codecs.Http;
using DotNetty.Framework;
using DotNetty.Framework.BaseModel;
using DotNetty.Framework.BaseTriggers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace iTool.Connector
{
    public class HttpEventTriggered<THttpContext> : AbstractHttpTrigger, IHttpEventTriggered<THttpContext>
        where THttpContext : AbstractHttpContext, new()
    {
        ILogger<HttpEventTriggered<THttpContext>> logger;

        public HttpEventTriggered(ILogger<HttpEventTriggered<THttpContext>> logger)
        {
            this.logger = logger;
        }

        public async Task ActionAsync(THttpContext httpContext)
        {
            //var worker = base.GetHttpWorker(httpContext);
            var worker = base.GetApiWorker(httpContext);

            if (worker != default)
            {
                Dictionary<string, string> parameters = new Dictionary<string, string>();

                foreach (var item in worker.parameters)
                {
                    parameters.TryAdd(item.Name, item.Value);
                }

                httpContext.ResponseBody =
                    await AssemblyUtils
                    .InvokeMethod(worker.worker.Instance, worker.worker.Method, parameters, t => t == typeof(AbstractHttpContext) ? httpContext : null);
            }
            else
            {
                httpContext.ResponseStatus = HttpResponseStatus.NotFound;
            }

            //if (worker == null)
            //{
            //    httpContext.ResponseBody = JsonConvert.SerializeObject(new
            //    {
            //        Code = 400,
            //        Error = "router is null"
            //    });

            //    return;
            //}
            //else
            //{
            //}

            //await worker.DoWorking(httpContext);

            //Console.WriteLine($"{httpContext.Path}:Action");
        }

        public async Task AfterAsync(THttpContext httpContext)
        {
            await Task.CompletedTask;
            //Console.WriteLine($"{httpContext.Path}:After");
        }

        public async Task BeforeAsync(THttpContext httpContext)
        {
            await Task.CompletedTask;
            //Console.WriteLine($"{httpContext.Path}:Before");
        }

        public async Task ErrorAsync(THttpContext httpContext, Exception exception)
        {
            this.logger.LogError(exception, "HttpEventTriggered OnError");
            await Task.CompletedTask;

        }

    }
}
